package com.zjsru.oneDay202209;

/**
 * @Author: likew
 * @Date: 2022/9/13
 *  最大交换
 *  输入: 2736
 * 输出: 7236
 * 解释: 交换数字2和数字7。
 */
public class MaximumSwap {
    
    public int maximumSwap(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int len = chars.length;
        int maxNum = num;
        for (int i = 0; i < len; i++) {
            //当i = 3时，i + 1就小于len，不会进入循环
            for (int j = i + 1; j < len; j++) {
                swap(chars, i, j);
                maxNum = Math.max(maxNum, Integer.parseInt(new String(chars)));
                //重新将数组交换回来，变成一开始的数字，保证遍历的有序性
                swap(chars, i, j);
            }
        }
        return maxNum;
    }
    
    private void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
    
    public static void main(String[] args) {
        MaximumSwap maximumSwap = new MaximumSwap();
        int num = 2736;
        System.out.println(maximumSwap.maximumSwap(num));
    }
}
